const api = require('../../utils/api')
const app = getApp()

Page({
    data: {
        searchName: "",
        peopleList: [],
        page: 0,
        size: 5,
        total: 0,
        loading: false,
        noMore: false,
        showModal: false,
        isEdit: false,
        startY: 0,
        isSearch: false,
        today: '',
        formData: {
            id: null,
            name: '',
            sex: '1',
            birthday: '',
            height: '',
            weight: ''
        }
    },

    onLoad() {
        const today = new Date().toISOString().split('T')[0];
        this.setData({ today });
        this.loadData()
    },

    loadData() {
        if ((this.data.noMore || this.data.loading) && !this.data.isSearch) {
            return;
        }
        if (this.data.isSearch) {
            this.setData({ page: 0, peopleList: [] });
        }
        this.setData({ loading: true })
        const { page, size, searchName } = this.data

        api.peopelPage(page + 1, size, searchName).then(res => {
            if (!res.data.code || res.data.code !== 1) {
                wx.showToast({
                    title: res.data.msg,
                    icon: "error"
                });
                return;
            }
            const { records, total } = res.data.data
            this.setData({
                peopleList: [...this.data.peopleList, ...records],
                page: page + 1,
                total: total,
                loading: false,
                noMore: (page + 1) * size >= total
            });
        })
    },

    loadMore() {
        this.setData({ isSearch: false });
        this.loadData();
    },

    handleTouchStart(e) {
        this.setData({ startY: e.touches[0].clientY });
    },
    handleTouchEnd(e) {
        const endY = e.changedTouches[0].clientY;
        const delta = this.data.startY - endY;
        if (delta > 50) { // 下滑距离阈值
            this.loadMore();
        }
    },

    handleSearchInput(e) {
        const searchName = e.detail.value.trim();
        this.setData({ searchName: searchName, isSearch: true });
        this.loadData();
    },

    handleInput(e) {
        const { field } = e.currentTarget.dataset;
        const { value } = e.detail;

        this.setData({
            [`formData.${field}`]: value
        });
    },

    handleSexChange(e) {
        const sex = e.detail.value;
        this.setData({
            'formData.sex': sex
        });
    },

    handleDateChange(e) {
        this.setData({
            'formData.birthday': e.detail.value
        });
    },

    addNew() {
        this.setData({
            showModal: true,
            isEdit: false,
            formData: {
                id: null,
                name: '',
                sex: '1',
                birthday: '',
                height: '',
                weight: ''
            }
        })
    },

    editItem(e) {
        const id = e.currentTarget.dataset.id
        const people = this.data.peopleList.find(u => u.id === id)

        this.setData({
            showModal: true,
            isEdit: true,
            formData: { ...people }
        })
    },

    deleteItem(e) {
        const id = e.currentTarget.dataset.id
        wx.showModal({
            title: '确认删除',
            content: '确定要删除这条记录吗？',
            success: res => {
                if (res.confirm) {
                    api.peopelDelete(id).then((res) => {
                        if (!res.data.code || res.data.code !== 1) {
                            wx.showToast({
                                title: res.data.msg,
                                icon: "error"
                            });
                            return;
                        }
                        this.setData({
                            peopleList: this.data.peopleList.filter(u => u.id !== id),
                            page: 0,
                            total: this.data.total - 1
                        });
                        wx.showToast({
                            title: '操作成功',
                            icon: 'success'
                        });
                    });
                }
            }
        })
    },

    submitForm(e) {
        const formData = this.data.formData;
        if(!formData.name || formData.name.length == 0) {
            wx.showToast({title: "姓名不能为空", icon: "none"});
            return;
        }
        if(!formData.birthday || formData.name.birthday == 0) {
            wx.showToast({title: "生日不能为空", icon: "none"});
            return;
        }
        if(!formData.sex || formData.name.sex == 0) {
            wx.showToast({title: "性别不能为空", icon: "none"});
            return;
        }
        if(formData.height && isNaN(formData.height)) {
            wx.showToast({title: "身高输入有误", icon: "none"});
            return;
        }
        if(formData.weight && isNaN(formData.weight)) {
            wx.showToast({title: "体重输入有误", icon: "none"});
            return;
        }
        const { isEdit } = this.data
        const request = isEdit
            ? api.peopelUpdate({ ...formData, id: this.data.formData.id })
            : api.peopelAdd(formData)

        request.then((res) => {
            if (!res.data.code || res.data.code !== 1) {
                wx.showToast({
                    title: res.data.msg,
                    icon: "error"
                });
                return;
            }
            this.hideModal();
            this.resetList();
            wx.showToast({
                title: '操作成功',
                icon: 'success'
            });
        });
    },

    hideModal() {
        this.setData({ showModal: false })
    },

    resetList() {
        this.setData({
            peopleList: [],
            page: 0,
            noMore: false,
            isSearch: false
        })
        this.loadData()
    }
})